const CommonApi = require("../../../api/common.js");
const UserApi = require("../../../api/user.js");
const utils = require('../../../utils/util.js');
const regExpUtil = require('../../utils/regExp.js');

Page({
  data: {
    _userInfo: null,
    step: 1,
    formModel: {
      phoneNumber: null,
      oldCode: null,
      oldCodeId: null,
      code: null,
      codeId: null,
    },
    phoneNumber: null,
    oldSafePhoneNumber: null,
    tickTip: '获取验证码',
    nTickTip: '获取验证码',
    timers: 60,
    nTimers: 60,
    countDown: null,
    nCountDown: null,
    dialogVisible: false,
    captchaConfirmData: {
      captchaValid: undefined,
      captchaId: undefined,
      captcha: undefined
    },
    captchaConfirmDataT: {
      captchaValid: undefined,
      captchaId: undefined,
      captcha: undefined
    },
  },

  onLoad(options) {},
  onReady() {},
  onShow() {
    let userInfo = wx.getStorageSync('userInfo');
    let safePhoneNumber = utils.safePhoneNumber(userInfo.phoneNumber);
    this.setData({
      _userInfo: userInfo, 
      phoneNumber: userInfo.phoneNumber,
      oldSafePhoneNumber: safePhoneNumber,
    });
  },
  onHide() {},
  onUnload() {},
  startInterval(){
    let that = this;

    if (that.data.step == 1) {
      let countDownNum = that.data.timers;
      that.data.countDown = setInterval(()=>{
        if (countDownNum < 1) {
          that.setData({tickTip: '获取验证码', timers: 60});
          clearInterval(that.data.countDown);
        } else {
          countDownNum--;
          that.setData({
            timers: countDownNum,
            tickTip: countDownNum+'s后重发'
          })
        }
      }, 1000)
    } else if (that.data.step == 2) {
      let countDownNum = that.data.nTimers;
      that.data.nCountDown = setInterval(()=>{
        if (countDownNum < 1) {
          that.setData({nTickTip: '获取验证码', nTimers: 60});
          clearInterval(that.data.nCountDown);
        } else {
          countDownNum--;
          that.setData({
            nTimers: countDownNum,
            nTickTip: countDownNum+'s后重发'
          })
        }
      }, 1000)
    }
  },
  getVerifyCode(){
    if (this.data.step == 1) {
      if (this.data.phoneNumber != null) {
        if (this.data.tickTip != '获取验证码') return;
        this.setData({dialogVisible: true});
      }
    } else if (this.data.step == 2) {
      if (this.data.nTickTip != '获取验证码') return;
      if (!this.data.formModel.phoneNumber) {
        wx.showToast({icon: 'none', title: '请输入手机号码'})
      } else if (this.data.formModel.phoneNumber && !regExpUtil.isPhoneNumber(this.data.formModel.phoneNumber)) {
        wx.showToast({icon: 'none', title: '请输入正确的手机号码'})
      } else {
        this.setData({
          phoneNumber: this.data.formModel.phoneNumber,
          dialogVisible: true
        });
        console.log(this.data.phoneNumber);
      }
    }
  },
  // 获取图形验证码弹窗传递来的数据
  getCaptchaData(e){
    console.log(e);
    if (this.data.step == 1) {
      this.setData({
        dialogVisible: false, 
        'captchaConfirmData.captcha': e.detail.captcha,
        'captchaConfirmData.captchaId': e.detail.captchaId,
      })
    } else if (this.data.step == 2) {
      this.setData({
        dialogVisible: false, 
        'captchaConfirmDataT.captcha': e.detail.captcha,
        'captchaConfirmDataT.captchaId': e.detail.captchaId,
      })
    }
    this.sendModifyPhoneNumberSms()
  },
  // 关闭图形验证码弹窗
  closeModal(){
    this.setData({
      dialogVisible: false, 
    })
  },
  // 发送修改手机号验证码
  sendModifyPhoneNumberSms(){
    let phoneNumber = this.data.step == 1 ? this.data.phoneNumber : this.data.formModel.phoneNumber;
    let captchaId = this.data.step == 1 ? this.data.captchaConfirmData.captchaId : this.data.captchaConfirmDataT.captchaId;
    let code = this.data.step == 1 ? this.data.captchaConfirmData.captcha : this.data.captchaConfirmDataT.captcha;

    CommonApi.sendModifyPhoneNumberSms({phoneNumber: phoneNumber, code: code, captchaId: captchaId}).then(res=>{
      if (res.retCode == "000000" && res.errCode == "000000") {
        this.setData({msgSend: true});
        if (this.data.step == 1) {
          this.setData({['formModel.oldCodeId']: res.data})
        } else if (this.data.step == 2) {
          this.setData({['formModel.codeId']: res.data})
        }
        wx.showToast({icon: 'success', title: '发送验证码成功'});
        this.startInterval();
      } else {
        wx.showToast({icon: 'error', title: res.errMsg});
      }
    })
  },
  // 校验短信验证码
  checkSms(_phoneNumber, _code, _codeId){
    CommonApi.checkSms({phoneNumber: _phoneNumber, code: _code, codeId: _codeId}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        console.log(res);
        if (!res.data) {
          wx.showToast({icon: 'error', title: '验证码错误'});
        } else {
          if (this.data.step == 1) {
            this.setData({step: 2})
          } else if (this.data.step == 2) {
            this.modifyPhoneNumber()
          }
        }
      } else {
        wx.showToast({icon: 'error', title: '验证码错误'});
      }
    })
  },
  modifyPhoneNumber(){
    UserApi.modifyPhoneNumber({...this.data.formModel}).then(res=>{
      if (res.retCode == "000000" && res.errCode == "000000") {
        wx.showToast({icon: 'none', title: res.errMsg})
        this.setData({
          ['formModel.phoneNumber']: null,
          ['formModel.oldCode']: null,
          ['formModel.oldCodeId']: null,
          ['formModel.code']: null,
          ['formModel.codeId']: null,
          phoneNumber: null,
        })
        setTimeout(()=>{
          wx.removeStorageSync('token')
          wx.removeStorageSync('userInfo')
          wx.removeStorageSync('userService')
          wx.removeStorageSync('tokenExpire')
          wx.redirectTo({
            url: '/packageA/pages/login/index?redirect_uri=/pages/index/index&redirect_uri_type=tab',
          })
        }, 2000)
      } else {
        wx.showToast({icon: 'none', title: res.errMsg});
      }
    })
  },
  handleInput(e){
    let target = e.currentTarget.dataset.item;
    let value = e.detail.value;
    if (target == 'oldCode') {
      this.setData({['formModel.oldCode']: value})
    } else if (target == 'phoneNumber') {
      this.setData({['formModel.phoneNumber']: value})
    } else if (target == 'code') {
      this.setData({['formModel.code']: value})
    }
  },
  goNext(){
    if (!this.data.formModel.oldCode) {
      wx.showToast({icon: 'none',title: '请输入验证码'})
    } else if (this.data.formModel.oldCode && this.data.formModel.oldCode.length!=6) {
      wx.showToast({icon: 'none',title: '请输入正确的验证码'})
    } else if (this.data.formModel.oldCode && this.data.formModel.oldCode.length==6) {
      this.checkSms(this.data.phoneNumber, this.data.formModel.oldCode, this.data.formModel.oldCodeId);
    }
  },
  submitForm(){
    if (!this.data.formModel.phoneNumber) {
      wx.showToast({icon: 'none',title: '请输入手机号'})
    } else if ((this.data.formModel.phoneNumber && !regExpUtil.isPhoneNumber(this.data.formModel.phoneNumber))) {
      wx.showToast({icon: 'none',title: '请输入正确的手机号码'})
    } else if (!this.data.formModel.code) {
      wx.showToast({icon: 'none',title: '请输入验证码'})
    } else if (this.data.formModel.code && this.data.formModel.code.length != 6) {
      wx.showToast({icon: 'none',title: '请输入正确的验证码'})
    } else {
      this.checkSms(this.data.formModel.phoneNumber, this.data.formModel.code, this.data.formModel.codeId);
    }
  },
  
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
})